# ----------------------------------------------------------------------------
#       Copyright (C) 2013-2014 Huynh Vi Lam  <domovilam@gmail.com>
#
#       This file is part of pimucha.
#
#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#	
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#	
#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.
# ----------------------------------------------------------------------------



# ----------------------------------------------------------------------------
# TellStick Duo  additionnal functions
# with Python 2.7.x  and 3.x
# ----------------------------------------------------------------------------
# Company Telldus Technologies
# ----------------------------
# - Website: http://www.telldus.com
# - Documentation and source code TellStick Duo is used as base for development of scripts
# ----------------------------------------------------------------------------


import logging,time

logger = logging.getLogger()

RequestCmd = {
   'STAT':('V+',5,'Status : Version request "V+"'),
   'VERS':('V+',5,'Version request  "V+"'),
   }



def requestcmd(dev,rcmd):
    if rcmd in RequestCmd:
        seq, lenresp, msg = RequestCmd[rcmd]
        logger.debug("Request %s to controller...",msg)
        nb = dev.write(seq)
        logger.debug("Nb caracters write to controller : %s",repr(nb))
        time.sleep(0.3)
        res = dev.read(100)
        if len(res) == 0:
            return None
        if res[0:2] == b"+W":
            logger.debug("Event incoming from controller : %s",repr(res))
            r = res
        else:
            r = res[0:lenresp]
            logger.debug("Response from controller : %s",repr(r))
        return r
    return None

